package com.fzu.mmdbproxyframework.model;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.fzu.mmdbproxyframework.context.ConfigContext;
import com.fzu.mmdbproxyframework.util.StringUtil;

public class MysqlDB extends DBAbstract {
	private String Mode; 	
	public DataSource masterDataSource;
	public DataSource slaveDataSource;
	public List<DataSource> dataSourceList = new LinkedList<DataSource>();
	private List<Table> tableList;
	private List<String> tableNameList;
	public String DBNodeName;
	public String DBNodeType;
	public  String DBName;
	public String port;
	public String passwd;
	public boolean active;
	public MMDataNodeCluster cluster; 
	
	private MysqlDB() {
	}
	
	
	/**
	 * @param cluster
	 */
	public MysqlDB(MMDataNodeCluster cluster) {
		super();
		this.cluster = cluster;
	}

	public List<String> create_insertSqlByTable(Table table) throws  SQLException{
		List<String>  strList = new ArrayList<String>();
		//INSERT INTO table1(id, name, address) VALUES(1, ygl, 'beijing')
			ResultSet rs_Table=getConnection().createStatement().executeQuery("select * from "+table.getName()); 
			while(rs_Table.next()){
				String Insert_str = "insert into `"+table.getName()+"` (";		     
				for(Map<String, String> columns : table.getColumns_List()){
					Insert_str += columns.get("COLUMN_NAME")+", ";
				}
				Insert_str = StringUtil.rmLastDot(Insert_str);
				Insert_str +=") VALUES(";
				for(Map<String, String> columns : table.getColumns_List()){
					String colum_value = rs_Table.getString(columns.get("COLUMN_NAME"));
					if(colum_value == null){
						Insert_str +=""+colum_value+",";
					}else{
						Insert_str +="'"+colum_value+"',";
					}					
				}
				Insert_str = StringUtil.rmLastDot(Insert_str)+");";
//				System.out.println("Insert_str="+Insert_str);
				strList.add(Insert_str);
			}
			
		
		return strList;
	}
	
	public List<String> create_AllinsertSql() throws SQLException{
		List<String>  strList = new ArrayList<String>();
		for(Table table : tableList){//INSERT INTO table1(id, name, address) VALUES(1, ygl, 'beijing')
			ResultSet rs_Table=getConnection().createStatement().executeQuery("select * from "+table.getName()); 
			while(rs_Table.next()){
				String Insert_str = "insert into `"+table.getName()+"` (";		     
				for(Map<String, String> columns : table.getColumns_List()){
					Insert_str += columns.get("COLUMN_NAME")+", ";
				}
				Insert_str = StringUtil.rmLastDot(Insert_str);
				Insert_str +=") VALUES(";
				for(Map<String, String> columns : table.getColumns_List()){
					String colum_value = rs_Table.getString(columns.get("COLUMN_NAME"));
					if(colum_value == null){
						Insert_str +=""+colum_value+",";
					}else{
						Insert_str +="'"+colum_value+"',";
					}					
				}
				Insert_str = StringUtil.rmLastDot(Insert_str)+");";
//				System.out.println("Insert_str="+Insert_str);
				strList.add(Insert_str);
			}
			
		}
		return strList;
		  
	}
	
	public List<Table> creatTableList() throws SQLException{
		tableList = new ArrayList<Table>();
		System.out.println("getMasterDataSource().getUrl()="+getMasterDataSource().getUrl());
		System.out.println("getMasterDataSource().getDbName()="+getMasterDataSource().getDbName());
		String tables_sql="SELECT * FROM information_schema.TABLES WHERE TABLE_SCHEMA = '"+getMasterDataSource().getDbName()+"'";
		ResultSet rs2 = getConnection().createStatement().executeQuery(tables_sql);
		while(rs2.next()){	
			Table table =new Table();
			table.setName(rs2.getString("TABLE_NAME"));
			table.getTable_attributes().put("TABLE_NAME", rs2.getString("TABLE_NAME"));
			table.getTable_attributes().put("TABLE_TYPE", rs2.getString("TABLE_TYPE"));
			table.getTable_attributes().put("ENGINE", rs2.getString("ENGINE"));
			table.getTable_attributes().put("UPDATE_TIME", rs2.getString("UPDATE_TIME"));
			table.getTable_attributes().put("TABLE_COLLATION", rs2.getString("TABLE_COLLATION"));
			table.getTable_attributes().put("AUTO_INCREMENT", rs2.getString("AUTO_INCREMENT"));
//			System.out.println("-表名---"+table.getName());
//			System.out.println(rs2.getString("TABLE_NAME"));
//			System.out.println(rs2.getString("TABLE_TYPE"));
//			System.out.println(rs2.getString("ENGINE"));
//			System.out.println(rs2.getString("UPDATE_TIME"));
//			System.out.println(rs2.getString("TABLE_COLLATION"));
//			System.out.println(rs2.getString("AUTO_INCREMENT"));
//			System.out.println("这张表属性信息结束");
			tableList.add(table);
			buidTableColumnsAttribute(table);
		}
		setTableList(tableList);
		for(DataSource datasource:getDataSourceList()){
			datasource.setTableList(tableList);
		}
		System.out.println("creatTableList");
		return tableList;
	}
	
	private void buidTableColumnsAttribute(Table table) throws SQLException{
		String information_schema_COLUMNS="SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'examDB' and TABLE_NAME='"+table.getName()+"'"  ;
		Connection conn = getConnection();
		ResultSet rs1 = conn.createStatement().executeQuery(information_schema_COLUMNS);
		System.out.println("-表名---"+table.getName());
		while(rs1.next()){
			Map<String, String> columns_attributes = new HashMap<String, String>();
			columns_attributes.put("COLUMN_NAME",rs1.getString("COLUMN_NAME"));
			columns_attributes.put("COLUMN_DEFAULT",rs1.getString("COLUMN_DEFAULT"));
			columns_attributes.put("IS_NULLABLE",rs1.getString("IS_NULLABLE"));
			columns_attributes.put("CHARACTER_SET_NAME",rs1.getString("CHARACTER_SET_NAME"));
			columns_attributes.put("COLUMN_TYPE",rs1.getString("COLUMN_TYPE"));
			columns_attributes.put("COLUMN_KEY",rs1.getString("COLUMN_KEY"));
			columns_attributes.put("EXTRA",rs1.getString("EXTRA"));
			columns_attributes.put("PRIVILEGES",rs1.getString("PRIVILEGES"));
			columns_attributes.put("COLUMN_COMMENT",rs1.getString("COLUMN_COMMENT"));
//			System.out.println(rs1.getString("COLUMN_NAME"));
//			System.out.println(rs1.getString("COLUMN_DEFAULT"));
//			System.out.println(rs1.getString("IS_NULLABLE"));
//			System.out.println(rs1.getString("CHARACTER_SET_NAME"));
//			System.out.println(rs1.getString("COLUMN_TYPE"));
//			System.out.println(rs1.getString("COLUMN_KEY"));
//			System.out.println(rs1.getString("EXTRA"));
//			System.out.println(rs1.getString("PRIVILEGES"));
//			System.out.println(rs1.getString("COLUMN_COMMENT"));
			table.getColumns_List().add(columns_attributes);
		}
//		System.out.println("这张表信息结束");
		
	}
	
	public java.sql.Connection getConnection() throws SQLException{
		//获取当前master的数据库链接
		java.sql.Connection conn= null;		
		conn=getMasterDataSource().getConnection();
//		System.out.println("获取当前master的数据库链接="+conn.hashCode());
		return conn;
	}
	
	public DataSource getMasterDataSource() {
		if(masterDataSource == null){
//			if(ConfigContext.getMaster_Slave().equalsIgnoreCase("true")){
				System.out.println("dataSourceList.size()="+dataSourceList.size());		
				for(DataSource dataSource :dataSourceList){
					if(dataSource.getType().equalsIgnoreCase("master") && !dataSource.isShutdown()){
						setMasterDataSource(dataSource);
						System.out.println("取出来的 masterDataSource="+masterDataSource.getDataSourcename());
					}
				}
//			}
		}
		
		return masterDataSource;
	}
	public void setMasterDataSource(DataSource masterDataSource) {
		this.masterDataSource = masterDataSource;
	}
	public DataSource getSlaveDataSource() {
		if(cluster.getConfigContext().getMaster_Slave().equalsIgnoreCase("true")){
			for(DataSource dataSource :dataSourceList){
				if(dataSource.getType().equalsIgnoreCase("slave") && !dataSource.isShutdown()){
					slaveDataSource =dataSource;
				}
			}
		}
		
		return slaveDataSource;
	}
	public void setSlaveDataSource(DataSource slaveDataSource) {
		this.slaveDataSource = slaveDataSource;
	}

	@Override
	public String getMode() {
		return Mode;
	}
	
	@Override
	public void setMode(String mode) {
		this.Mode = mode;
	}
	
	@Override
	public void setDBNodeName(String name) {
		this.DBNodeName=name;
	}
	
	@Override
	public void setDBNodeType(String type) {
		this.DBNodeType=type;
	}
	

	public void setDataSourceList(List<DataSource> DataSourceList) {
		this.dataSourceList = DataSourceList;
	}

	public List<DataSource> getDataSourceList() {
		return dataSourceList;
	}

	@Override
	public String getPort() {
		return port;
	}

	@Override
	public String getPasswd() {
		return passwd;
	}
	
	@Override
	public List<Table> getTableList() {
		
		return tableList;
	}

	public void setTableList(List<Table> tableList) {
		this.tableList = tableList;
	}

	public boolean isActive() {
		return active;
	}

	public void setActive(boolean active) {
		this.active = active;
	}

	public String getDBName() {
		return DBName;
	}

	public void setDBName(String dBName) {
		DBName = dBName;
	}

	public List<String> getTableNameList() {
		return tableNameList;
	}

	public void setTableNameList(List<String> tableNameList) {
		this.tableNameList = tableNameList;
	}
}
